<?php

class Lib_Profiler implements \Doctrine\DBAL\Logging\SQLLogger
{

    private $start;

    private $logger;

    public function __construct()
    {
        $writer = new Zend_Log_Writer_Firebug();
        $this->logger = new Zend_Log($writer);
    }

    /**
     * Logs a SQL statement somewhere.
     *
     * @param string $sql The SQL to be executed.
     * @param array $params The SQL parameters.
     * @param float $executionMS The microtime difference it took to execute this query.
     * @return void
     */
    public function startQuery($sql, array $params = null, array $types = null)
    {
        $this->start = microtime(true);
        $this->logger->log($sql, Zend_Log::INFO);
        if (count($params)) {
            $this->logger->log("Params:" . self::toString($params), Zend_Log::DEBUG);
        }
    }

    /**
     * Mark the last started query as stopped. This can be used for timing of queries.
     *
     * @return void
     */
    public function stopQuery()
    {
        $timeTaken = microtime(true) - $this->start;
        $this->logger->log("Total query time: " . number_format($timeTaken, 6) ."s", Zend_Log::DEBUG);
    }

    public static function toString(array $array)
    {
        $string = '';
        foreach ($array as $key => $value) {
            if ($value instanceof DateTime) {
                $value = $value->format("Y-m-d H:i");
            }
            $string = "$key => $value; ";
        }
        return $string;
    }
}
